package spring.mvc.web.test.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import spring.mvc.web.test.mapper.UserMapper;
import spring.mvc.web.test.pojo.entity.User;
import spring.mvc.web.test.pojo.po.UserPo;
import spring.mvc.web.test.pojo.vo.RespCodeTypeEnum;
import spring.mvc.web.test.pojo.vo.RespResult;
import spring.mvc.web.test.service.UserService;


import javax.annotation.Resource;
import javax.xml.transform.Result;

/**
 * 用户接口的实现类
 */
@Service

public class UserServiceImpl implements UserService {

    @Resource
    UserMapper userMapper;

    @Override
    public RespResult register(UserPo userPo) throws RuntimeException {
        User user = new User();
        BeanUtils.copyProperties(userPo, user);
        int insert = userMapper.insert(user);
        System.out.println(user);
        RespResult respResult = new RespResult();
        if (insert == 1) {
            System.out.println(insert);
            respResult.setData(RespCodeTypeEnum.SUCCESS.getValue());
        } else {
            respResult.setData(RespCodeTypeEnum.FAILED.getValue());
            RuntimeException runtimeException = new RuntimeException("用户不存在");
            throw runtimeException;
        }
        return respResult;
    }

    @Override
    public RespResult<UserPo> login(UserPo userPo) throws RuntimeException {
        String username = userPo.getUsername();
        String password = userPo.getPassword();
        User user = userMapper.selectByUserName(username, password);
        BeanUtils.copyProperties(userPo,user);
        System.out.println(userPo);
        RespResult respResult = new RespResult();
        if (user != null) {
            if (user.getUsername().equals(username) && (user.getPassword().equals(password))) {
                System.out.println(user);
                System.out.println("登录成功");
                respResult.setData(RespCodeTypeEnum.SUCCESS.getValue());
                respResult.setMessage("登录成功");
            } else if (!user.getUsername().equals(username)) {
                //用户不存在，抛出异常
                RuntimeException runtimeException = new RuntimeException("用户不存在");
                throw runtimeException;
            } else if (!user.getPassword().equals(password)) {
                //密码错误
                RuntimeException runtimeException = new RuntimeException("密码错误");
                throw runtimeException;
            } else if (user == null) {
                System.out.println(user);
                respResult.setData(RespCodeTypeEnum.FAILED.getValue());
                RuntimeException runtimeException = new RuntimeException("用户不存在");
                throw  runtimeException;
            } else {
                    throw  new RuntimeException("没有登录成功");

            }
        }
        return respResult;
    }
}



